package com.amazon.shop.controller;


import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.Bank;
import com.amazon.shop.entity.FinanceBalance;
import com.amazon.shop.entity.Recharge;
import com.amazon.shop.entity.auth.Apartments;
import com.amazon.shop.entity.auth.Roles;
import com.amazon.shop.entity.auth.Users;
import com.amazon.shop.entity.auth.UsersRoles;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.*;
import com.amazon.shop.service.impl.PermissionsServiceImpl;
import com.amazon.shop.service.impl.UsersServiceImpl;
import com.amazon.shop.utils.CommonResult;
import com.amazon.shop.vo.RechargeSearchVo;
import com.amazon.shop.vo.RechargeVo;
import com.amazon.shop.vo.WithdrawalVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郭非
 * @since 2021-06-27
 */
@RestController
@RequestMapping("/shop/recharge")
@Api(tags = "充值提现模块")
public class RechargeController {
    @Resource
    private RechargeService rechargeService;
    @Resource
    private PermissionsServiceImpl permissionsService;
    @Resource
    private UsersServiceImpl usersService;
    @Resource
    private BankService bankService;
    @Resource
    private FinanceBalanceService financeBalanceService;
    @Resource
    private RolesService rolesService;
    @Resource
    private UsersRolesService usersRolesService;
    @Resource
    private ApartmentsService apartmentsService;

    /**
     * 充值
     *
     * @param rechargeVo
     * @param token
     * @return
     */
    @SystemLog(value = "充值")
    @PostMapping("/recharge")
    @ApiOperation(value = "充值")
    @Transactional
    public CommonResult recharge(@RequestBody RechargeVo rechargeVo, String token) {
        Recharge recharge = new Recharge();
        //属性对拷
        BeanUtils.copyProperties(rechargeVo, recharge);

        //根据银行名称查询银行编号
        String bankName = rechargeVo.getBank();
        QueryWrapper<Bank> bankQueryWrapper = new QueryWrapper<>();
        bankQueryWrapper.eq("bank", bankName);
        Bank bank = bankService.getOne(bankQueryWrapper);
        String bankId = bank.getBankId();
        recharge.setBankId(bankId);

        //处理充值
        BigDecimal payment = rechargeVo.getPayment();
        recharge.setPayment(payment);

        //自定义充值编号
        String rechargeId = UUID.randomUUID().toString().replace("-", "");
        recharge.setRechargeId(rechargeId);

        //保存充值信息
        boolean save = rechargeService.save(recharge);
        if (save) {
            String userRealName = usersService.getUserRealName(token);
            return CommonResult.success("保存充值信息成功")
                    .put("list", rechargeId)
                    .put("salesman", userRealName);
        } else {
            return CommonResult.error("保存充值信息失败");
        }
    }

    /**
     * 提现
     *
     * @param withdrawalVo
     * @param token
     * @return
     */
    @SystemLog(value = "提现")
    @PostMapping("/withdrawal")
    @ApiOperation(value = "提现")
    @Transactional
    public CommonResult withdrawal(@RequestBody WithdrawalVo withdrawalVo, String token) {
        boolean flag = permissionsService.getPermissionList(token, "55");
        if (flag) {
            Recharge recharge = new Recharge();
            //属性对拷
            BeanUtils.copyProperties(withdrawalVo, recharge);

            //根据银行名称查询银行编号
            String bankName = withdrawalVo.getBank();
            QueryWrapper<Bank> bankQueryWrapper = new QueryWrapper<>();
            bankQueryWrapper.eq("bank", bankName);
            Bank bank = bankService.getOne(bankQueryWrapper);
            String bankId = bank.getBankId();
            recharge.setBankId(bankId);

            //处理充值
            BigDecimal withdrawal = withdrawalVo.getWithdrawal();
            recharge.setCash(withdrawal);

            //自定义提现编号
            String rechargeId = UUID.randomUUID().toString().replace("-", "");
            recharge.setRechargeId(rechargeId);

            //保存充值信息
            boolean save = rechargeService.save(recharge);
            if (save) {
                String userRealName = usersService.getUserRealName(token);
                return CommonResult.success("保存提现信息成功")
                        .put("list", rechargeId)
                        .put("salesman", userRealName);
            } else {
                return CommonResult.error("保存提现信息失败");
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 查询充值提现列表
     *
     * @param token
     * @return
     */
    @GetMapping("/getRechargeList")
    @ApiOperation(value = "查询充值提现列表")
    public CommonResult getRechargeList(String token) {
        boolean flag = permissionsService.getPermissionList(token, "57");
        if (flag) {
            List<Recharge> rechargeList = rechargeService.list();
            List<RechargeSearchVo> rechargeSearchVos = rechargeList.stream().map((recharge) -> {
                RechargeSearchVo rechargeSearchVo = new RechargeSearchVo();
                //属性对拷
                BeanUtils.copyProperties(recharge, rechargeSearchVo);

                //处理充值和提现
                BigDecimal payment = recharge.getPayment();
                if (payment != null) {
                    rechargeSearchVo.setPayment(payment);
                }
                BigDecimal cash = recharge.getCash();
                if (cash != null) {
                    rechargeSearchVo.setCash(cash);
                }

                try {
                    //根据银行编号查询银行名称
                    String bankId = recharge.getBankId();
                    Bank bank = bankService.getById(bankId);
                    String bankName = bank.getBank();
                    //设置银行名称
                    rechargeSearchVo.setBank(bankName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return rechargeSearchVo;
            }).collect(Collectors.toList());
            return CommonResult.success().put("rechargeSearchVos", rechargeSearchVos);
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 更新充值状态
     *
     * @param token
     * @param rechargeSearchVo
     * @return
     */
    @SystemLog(value = "更新充值状态")
    @PostMapping("/updatePaymentStatus")
    @ApiOperation(value = "更新充值状态")
    @Transactional
    public CommonResult updatePaymentStatus(String token, @RequestBody RechargeSearchVo rechargeSearchVo) {
        String apartmentId = getApartmentId(token);
        String userRealName = usersService.getUserRealName(token);

        //获取充值金额
        BigDecimal payment = rechargeSearchVo.getPayment();
        Recharge recharge = new Recharge();
        BeanUtils.copyProperties(rechargeSearchVo, recharge);


        //根据部门编号查询智赢余额
        QueryWrapper<FinanceBalance> financeBalanceQueryWrapper = new QueryWrapper<>();
        financeBalanceQueryWrapper.eq("apartment_id", apartmentId);
        int count = financeBalanceService.count(financeBalanceQueryWrapper);
        if (count == 0) {
            FinanceBalance financeBalance = new FinanceBalance();
            //无充值记录新建
            financeBalance.setApartmentId(apartmentId);
            financeBalance.setBalance(payment);
            financeBalanceService.save(financeBalance);

            //更新充值提现信息
            rechargeService.updateById(recharge);

            return CommonResult.success("更新充值状态成功")
                    .put("list", apartmentId)
                    .put("salesman", userRealName);
        } else {
            //有充值记录增加
            FinanceBalance financeBalance = financeBalanceService.getById(apartmentId);
            BigDecimal balance = financeBalance.getBalance();
            BigDecimal newBalance = balance.add(payment);
            financeBalance.setBalance(newBalance);
            financeBalanceService.updateById(financeBalance);
            //更新充值提现信息
            rechargeService.updateById(recharge);

            return CommonResult.success("更新充值状态成功")
                    .put("list", apartmentId)
                    .put("salesman", userRealName);
        }
    }

    /**
     * 更新提现状态
     *
     * @param token
     * @param rechargeSearchVo
     * @return
     */
    @SystemLog(value = "更新提现状态")
    @PostMapping("/updateWithdrawalStatus")
    @ApiOperation(value = "更新提现状态")
    @Transactional
    public CommonResult updateWithdrawalStatus(String token, @RequestBody RechargeSearchVo rechargeSearchVo) {
        boolean flag = permissionsService.getPermissionList(token, "58");
        if (flag) {
            //根据token查询用户信息
            String apartmentId = getApartmentId(token);

            BigDecimal withdrawal = rechargeSearchVo.getCash();
            Recharge recharge = new Recharge();
            BeanUtils.copyProperties(rechargeSearchVo, recharge);

            FinanceBalance financeBalance = financeBalanceService.getById(apartmentId);
            if (financeBalance == null) {
                throw new CustomException(ReturnConstant.NO_ACCOUNT_ERROR_CODE
                        , ReturnConstant.NO_ACCOUNT_ERROR_MESSAGE);
            } else {
                //有提现记录减少
                BigDecimal balance = financeBalance.getBalance();
                BigDecimal newBalance = balance.subtract(withdrawal);
                if (newBalance.doubleValue() > 0) {
                    financeBalance.setBalance(newBalance);
                    //更新智赢余额信息
                    financeBalanceService.updateById(financeBalance);

                    //更新充值提现信息
                    rechargeService.updateById(recharge);
                    String rechargeId = recharge.getRechargeId();
                    String userRealName = usersService.getUserRealName(token);
                    return CommonResult.success("提现状态更新成功")
                            .put("list", rechargeId).put("salesman", userRealName);
                } else {
                    throw new CustomException(ReturnConstant.BALANCE_NOT_ENOUGH_CODE
                            , ReturnConstant.BALANCE_NOT_ENOUGH_MESSAGE);
                }
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }

    /**
     * 获取部门编号
     *
     * @param token
     * @return
     */
    private String getApartmentId(String token) {
        //根据token查询用户信息

        QueryWrapper<Users> usersQueryWrapper = new QueryWrapper<>();
        usersQueryWrapper.eq("token", token);
        Users users = usersService.getOne(usersQueryWrapper);

        //根据用户编号查询角色信息
        String userId = users.getUserId();
        QueryWrapper<UsersRoles> usersRolesQueryWrapper = new QueryWrapper<>();
        usersRolesQueryWrapper.eq("user_id", userId);
        UsersRoles usersRoles = usersRolesService.getOne(usersRolesQueryWrapper);

        //根据角色编号查询部门信息
        String roleId = usersRoles.getRoleId();
        Roles roles = rolesService.getById(roleId);

        //根据部门名称查询部门编号
        String apartmentName = roles.getApartmentName();
        QueryWrapper<Apartments> apartmentsQueryWrapper = new QueryWrapper<>();
        apartmentsQueryWrapper.eq("apartment_name", apartmentName);
        Apartments apartments = apartmentsService.getOne(apartmentsQueryWrapper);
        return apartments.getApartmentId();
    }
}

